<template>
  <div>
    <div id="container"></div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'map-page',
  async mounted() {
    const { BMapGL } = window
    const map = new BMapGL.Map('container')
    const obj = JSON.parse(window.localStorage.getItem('city'))
    const cityName = obj ? obj.label + '市' : '上海市'
    console.log(cityName)
    map.centerAndZoom(cityName, 12) // 初始化地图,设置中心点坐标和地图级别

    const res = await axios.get(
      'http://liufusong.top:8080/area/map?id=' + obj.value
    )
    console.log(res)
    res.data.body.forEach((item) => {
      const point = new BMapGL.Point(item.coord.longitude, item.coord.latitude)
      const content = item.label + '<br>' + item.count
      const label = new BMapGL.Label(content, {
        // 创建文本标注
        position: point, // 设置标注的地理位置
        offset: new BMapGL.Size(10, 20) // 设置标注的偏移量
      })
      map.addOverlay(label) // 将标注添加到地图中

      label.setStyle({
        // 设置label的样式
        color: '#fff',
        backgroundColor: 'green',
        fontSize: '14px',
        borderRadius: '50%',
        width: '60px',
        height: '60px',
        padding: '20px',
        textAlign: 'center',
        border: '2px solid #1E90FF'
      })

      label.addEventListener('click', async function () {
        const point = new BMapGL.Point(
          item.coord.longitude,
          item.coord.latitude
        )
        map.centerAndZoom(point, 15)
        map.clearOverlays() // 移除覆盖物
        const res = await axios.get(
          'http://liufusong.top:8080/area/map?id=' + item.value
        )
        console.log(res)

        res.data.body.forEach((item) => {
          const point = new BMapGL.Point(
            item.coord.longitude,
            item.coord.latitude
          )
          const content = item.label + '<br>' + item.count
          const label = new BMapGL.Label(content, {
            // 创建文本标注
            position: point, // 设置标注的地理位置
            offset: new BMapGL.Size(10, 20) // 设置标注的偏移量
          })
          map.addOverlay(label) // 将标注添加到地图中

          label.setStyle({
            // 设置label的样式
            color: '#fff',
            backgroundColor: 'green',
            fontSize: '14px',
            borderRadius: '50%',
            width: '60px',
            height: '60px',
            padding: '20px',
            textAlign: 'center',
            border: '2px solid #1E90FF'
          })
        })
      })
    })
  },
  data() {
    return {}
  },
  methods: {}
}
</script>

<style scoped lang="less">
#container {
  height: 100vh;
}
</style>
